#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import xmpp_handlers

from rec import recProc
from todo import todoProc
from at import atProc,atSchedule
from cron import crProc,crSchedule
from md5crack import crackProc

class MainPage(webapp.RequestHandler):
	def get(self):
		self.response.headers['Content-Type'] = 'text/plain'
		self.response.out.write( CalBotHandler.helpmsg() )

class AtPage(webapp.RequestHandler):
	def get(self):
		atSchedule()
	
class CronPage(webapp.RequestHandler):
	def get(self):
		crSchedule()

class CalBotHandler(xmpp_handlers.CommandHandler):
	def crack_command(self, message=None):
		crackProc( self.BareJid(message.sender),message.arg )

	def rec_command(self, message=None):
		recProc( self.BareJid(message.sender),message.arg )

	def todo_command(self, message=None):
		todoProc( self.BareJid(message.sender),message.arg )

	def cron_command(self, message=None):
		crProc( self.BareJid(message.sender),message.arg )

	def at_command(self, message=None):
		atProc( self.BareJid(message.sender),message.arg )

	def num_command(self, message=None):
		if message.arg :
			try:
				result = str( eval(message.arg) ) 
			except :
				result = 'Wrong format expr:'+ message.arg

			message.reply(result)
		else:
			message.reply( '\\num 3**2+5*2' )

	def help_command(self, message=None):
		message.reply( self.helpmsg() )

	def unhandled_command(self, message):
		message.reply('for all commands,type \help')

	def text_message(self, message=None):	
		message.reply( self.helpmsg() )
	
	@classmethod
	def helpmsg(self):
		result = 'available commands:'
		members = dir(self)
		for item in members:
			if item<>'unhandled_command' and callable(getattr(self,item)):
				index = item.find('_command')
				if index <> -1 :
					result += '\n  \\'+ item[:index]
		return result

	@staticmethod
	def BareJid(jid):
		g = jid.split('/')
		return g[0]

def main():
    application = webapp.WSGIApplication(
			[	('/', MainPage), 
				('/_at',AtPage),
				('/_cr',CronPage),
				('/_ah/xmpp/message/chat/', CalBotHandler) ],
				debug=True)
    util.run_wsgi_app(application)


if __name__ == '__main__':
    main()
